// packageE/article/article.js
var app = getApp();
let innerAudioContext = null;
Component({
  properties: {
    datas: {
      type: null
    },
    component_id: {
      type: null
    },
    U_tabcontrol: {
      type: null
    },
    bottomShowBolIndex: {
      type: null
    },
    index: {
      type: null
    },
    bottomShowBol:{
      type:null
    },
    plugin_active: String
  },
  // 私有数据，可用于模板渲染
  data: {
    emptyImage: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/image.png',
    clientWidth: '375',
    language: '',

    active: "0",
    class_id: "0",
    list: [],
    categories: [],
    isLoadMore: true,
    page: 1,
    total_page: 0,
    pageSize: 12,
    noNotice: false,
    allLoaded: false, // 全部数据已经加载完成
    playInd: null,
    // 开始播放请求接口
    postStart: false,
    sliderShow:false
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      let language = wx.getStorageSync('langIndex');
      this.setData({
        'language': language.en
      });
      innerAudioContext = wx.createInnerAudioContext();
      this.init();
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });

    if (this.data.datas.get_style == 1 || this.data.datas.get_style == 3) {
      this.initData();
      //获取数据
      this.getNetData(this.data.datas);
    } else {
      this.setData({
        isLoadMore: false,
        allLoaded: true
      });
    }
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {
      innerAudioContext = wx.createInnerAudioContext();
      this.init();
    },
    hide() {
      innerAudioContext.stop();
      innerAudioContext.destroy();
    },
    resize() {},
  },
  observers:{
    'bottomShowBol':function(showbol){
      if(this.data.bottomShowBolIndex == this.data.index){
        this.getMoreData();
      }
    }
  },
  methods: {
    tapMethod(e){
      let item = e.currentTarget.dataset.item;
      if(item.playStatus){
        this.pause(e);
      }else{
        this.startPlayOrPause(e);
      }
    },
    checkNoticeVideo(aid){
      return new Promise((resolve, reject)=>{
        app._getNetWork({
          url: app.getNetAddresss("plugin.article-pay.api.index.paid"),
          data: {
            article_id:aid
          },
          success: (resdata) => {
            var res = resdata.data;
            resolve(res.result)
          },
          fail: function (res) {
            reject(res)
          }
        });
      })
    },
    async startPlayOrPause(e) {
      let item = e.currentTarget.dataset.item;
      if(item.is_pay == 1 || item.has_one_article_pay){
        let result =  await this.checkNoticeVideo(item.id);
        if(result == 0){
          //未付费
          wx.navigateTo({
            url: '/packageD/article/articleList/articleList?article_id=' + item.id
          });
          return
        }
      }
      let check = await this.checkPrivilege(item.id);
      if(check.result == 0){
        wx.showToast({
          title: check.msg,
          icon:'none',
          duration:1000
        })
        return
      }else{
        let i = e.currentTarget.dataset.i;
        let info = this.data.datas.get_style == 2?this.data.datas.list:this.data.list;
        if(!this.data.sliderShow ) this.setData({sliderShow : true})
        for (let k = 0; k < info.length; k++) {
          info[k].playStatus = false;
        }
        info[i].playStatus = true;
        if (this.data.playInd != i) {
          innerAudioContext.stop();
          this.data.postStart = false;
        }
        this.setData({
          playInd: i,
        })
        if(this.data.datas.get_style == 2){
          this.setData({
            ['datas.list']:this.data.datas.list
          })
        }else{
          this.setData({
            list:this.data.list
          })
        }
        innerAudioContext.src = encodeURI(item.audio_link);
        innerAudioContext.play();
      }
      
    },
    checkPrivilege(id){
      return new Promise((resolve, reject)=>{
        let urlStr = app.getNetAddresss("plugin.article.api.article.get-article");
        app._getNetWork({
          url: urlStr,
          data: {
            article_id:id
          },
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              resolve(res)
            }else{
              resolve(res)
            }
          },
          fail: function (res) {
            console.log(res);
          }
        });
      })
    },
    pause(e) {
      let i = e.currentTarget.dataset.i;
      (this.data.datas.get_style == 2?this.data.datas.list:this.data.list)[i].playStatus = false;
      this.data.postStart = true;
      if(this.data.datas.get_style == 2){
        this.setData({
          ['datas.list']:this.data.datas.list
        })
      }else{
        this.setData({
          list:this.data.list
        })
      }
      innerAudioContext.pause();
    },
    tapClose() {
      this.setData({
        sliderShow: false
      })
    },
    sildein(e) {
      var setvalue = e.detail.value / 100;
      var long = this.data.audio_length * setvalue;
      if(this.data.datas.get_style == 2){
        this.data.datas.list[this.data.playInd].playStatus = false;
        this.setData({
          ['datas.list']:this.data.datas.list
        })
      }else{
        this.data.list[this.data.playInd].playStatus = false;
        this.setData({
          list:this.data.list
        })
      }
      innerAudioContext.seek(long);
      innerAudioContext.play();
    },
    changeSilde(e){
      let setvalue = e.detail;
      let long = this.data.audio_length * (setvalue / 100);
      if(this.data.datas.get_style == 2){
        this.data.datas.list[this.data.playInd].playStatus = true;
        this.setData({
          ['datas.list']:this.data.datas.list
        })
      }else{
        this.data.list[this.data.playInd].playStatus = true;
        this.setData({
          list:this.data.list
        })
      }
      innerAudioContext.seek(long);
      innerAudioContext.play();
    },
    init() {
      innerAudioContext.onCanplay(() => {});
      innerAudioContext.onPlay(() => {
        this.startPostMethod()
      });
      innerAudioContext.onTimeUpdate(() => {
        setTimeout(() => {
          let smun = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
          var valueSlmin = parseInt(smun);
          this.setData({
            valueSlmin: valueSlmin,
            audio_length: innerAudioContext.duration,
          });
        }, 500);
      });
      innerAudioContext.onEnded((e) => {
        if(this.data.datas.get_style == 2){
          this.data.datas.list[this.data.playInd].playStatus = false;
        }else{
          this.data.list[this.data.playInd].playStatus = false;
        }
        if(this.data.datas.get_style == 2){
          this.setData({
            ['datas.list']:this.data.datas.list
          })
        }else{
          this.setData({
            list:this.data.list
          })
        }
        this.data.postStart = false;
      })
      innerAudioContext.onError((res) => {
        // wx.showToast({
        //   title: "播放错误",
        //   icon: "none",
        // });
      });
    },
    startPostMethod() {
      if (this.data.postStart == false) {
        let urlStr = app.getNetAddresss("plugin.article.api.article.clickAudioViews");
        let json = {
          article_id:''
        }
        if(this.data.datas.get_style == 2){
          json.article_id = this.data.datas.list[this.data.playInd].id;
        }else{
          json.article_id = this.data.list[this.data.playInd].id;
        }
        app._getNetWork({
          url: urlStr,
          data: json,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              if(this.data.datas.get_style == 2){
                this.data.datas.list[this.data.playInd].virtual_audio_views = res.data.virtual_audio_views;
                this.setData({
                  ['datas.list']:this.data.datas.list
                })
              }else{
                this.data.list[this.data.playInd].virtual_audio_views = res.data.virtual_audio_views;
                this.setData({
                  list:this.data.list
                })
              }
            }
          },
          fail: function (res) {
            console.log(res);
          }
        });
      } else {
        console.log('暂停过 postStart = true')
      }
    },
    initData() {
      if (innerAudioContext) {
        innerAudioContext.stop();
      }
      this.setData({
        page: 1,
        total_page: 0,
        isLoadMore: true,
        list: [],
        sliderShow:false
      });
    },
    //获取数据
    getNetData(data) {
      let that = this;

      if (data) {
        this.setData({
          noNotice: false,
          total_page: data.list.last_page,
          pageSize: data.list.per_page,
          isLoadMore: true
        });

        if (that.data.total_page <= 1) {
          this.setData({
            isLoadMore: false,
            allLoaded: true
          });
        }

        if (data.list.data && data.list.data.length > this.data.datas.get_number) {
          data.list.data.splice(this.data.datas.get_number, data.list.data.length - this.data.datas.get_number);
          this.setData({
            isLoadMore: false,
            allLoaded: true
          });
        }

        this.setData({
          list: data.list.data
        });

        if (data.cate) {
          this.setData({
            categories: data.cate,
            class_id: data.cate[0]&&this.data.datas.get_style!= 1 ? data.cate[0].id : "0",
            active: data.cate[0]&&this.data.datas.get_style!= 1 ? data.cate[0].id : "0",
          });
          if (data.cate.length <= 0) {
            this.setData({
              noNotice: true
            });
          }
        }

        return;
      }

      let json = {
        category_id: this.data.class_id,
        page: 1,
        pageSize: 12,
        show_audio: this.data.datas.show_audio,
        is_decorate: true
      };
      let urlStr = app.getNetAddresss("plugin.article.api.article.get-articles");
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              noNotice: false,
              total_page: res.data.articles.last_page,
              pageSize: res.data.articles.per_page,
              isLoadMore: true
            });
            if (that.data.total_page <= 1) {
              that.setData({
                isLoadMore: false,
                allLoaded: true
              });
            }
            if (res.data.categories.length <= 0) {
              that.setData({
                noNotice: true
              });
            }

            if (res.data.articles.data.length > this.data.datas.get_number) {
              res.data.articles.data.splice(this.data.datas.get_number, res.data.articles.data.length - this.data.datas.get_number);
              this.setData({
                isLoadMore: false,
                allLoaded: true
              });
            }

            that.setData({
              list: res.data.articles.data,
            });

          } else {
            that.setData({
              noNotice: true
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });

    },
    toNoticeInfo(e) {
      let item = e.currentTarget.dataset.item;
      console.log(item)
      if(item.has_one_article_pay){
        if(!item.has_one_record){
          wx.navigateTo({
            url: '/packageD/article/articleList/articleList?article_id=' + item.id
          });
          return
        }
      }
      if (item.type == 1) {
        wx.navigateTo({
          url: '/packageA/member/course/VoiceDetail/VoiceDetail?article_id=' + item.id
        });
      } else {
        wx.navigateTo({
          url: '/packageA/member/article/articleContent/articleContent?article_id=' + item.id
        });
      }

    },
    onClick(e) {
      let index = e.detail.index;
      console.log(this.data.categories, '188');
      this.initData();
      if (index === 0) {
        if (this.data.datas.get_style == 1) {
          //分类的"全部"只在get_style == 1的时候才出现
          this.setData({
            class_id: '0',
            active: '0'
          });
        } else {
          this.setData({
            class_id: this.data.categories[index].id,
            active: String(this.data.categories[index].id)
          });
        }
      } else {
        this.setData({
          class_id: this.data.datas.get_style == 1 ? this.data.categories[index - 1].id : this.data.categories[index].id,
          active: this.data.datas.get_style == 1 ? String(this.data.categories[index - 1].id) : String(this.data.categories[index].id)
        });
      }
      this.getNetData();
    },
    getMoreData() {
      let that = this;
      that.setData({
        isLoadMore: false
      });
      if (this.data.page >= this.data.total_page || this.data.list.length > this.data.datas.get_number) {
        that.setData({
          isLoadMore: false
        });
      } else {
        that.setData({
          page: this.data.page + 1
        });
        let json = {
          category_id: this.data.class_id,
          page: this.data.page,
          pageSize: this.data.pageSize,
          show_audio: this.data.datas.show_audio,
          is_decorate: true
        };
        let urlStr = app.getNetAddresss("plugin.article.api.article.get-articles");
        app._getNetWork({
          url: urlStr,
          data: json,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                total_page: res.data.articles.last_page,
              });
              if (this.data.page < this.data.total_page) {
                that.setData({
                  isLoadMore: true
                });
              } else {
                that.setData({
                  allLoaded: true
                });
              }

              let data = that.data.list.concat(res.data.articles.data);
              if (data.length > this.data.datas.get_number) {
                data.splice(this.data.datas.get_number, data.length - this.data.datas.get_number);
                that.setData({
                  isLoadMore: false,
                  allLoaded: true
                });
              }
              that.triggerEvent("setLoadMore", {
                isLoadMore: that.data.isLoadMore,
              });
              that.setData({
                list: data
              });

            } else {
              that.setData({
                page: that.data.page - 1,
                isLoadMore: false,
                allLoaded: true
              });
            }
          },
          fail: function (res) {
            console.log(res);
          }
        });
      }
    }
  }
});